const setDocumentTitle = function (title) {
  document.title = title
  const ua = navigator.userAgent
  // eslint-disable-next-line
  const regex = /\bMicroMessenger\/([\d\.]+)/
  if (regex.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
    const i = document.createElement('iframe')
    i.src = '/favicon.ico'
    i.style.display = 'none'
    i.onload = function () {
      setTimeout(function () {
        i.remove()
      }, 9)
    }
    document.body.appendChild(i)
  }
}

const handleStateChange = (title, prefix) => {
  const titles = [];
  if (title) {
    titles.push(title);
  }
  if (prefix) {
    titles.push(prefix);
  }
  const nextTitle = titles.join(' - ');
  if (nextTitle !== document.title) {
    setDocumentTitle(nextTitle);
  }
};

const DocumentTitle = {
  name: 'DocumentTitle',
  functional: true,
  inheritAttrs: false,
  props: {
    prefix: {
      type: String,
      required: false,
      default: process.env.VUE_APP_NAME || '管理平台', // eslint-disable-line
    },
    title: {
      type: String,
    },
  },
  // { props, data, children }
  // eslint-disable-next-line
  render(createElement, {props, children}) {
    handleStateChange(props.title, props.prefix);
    return children;
  },
};

DocumentTitle.install = function(Vue) {
  Vue.component(DocumentTitle.name, DocumentTitle);
};

export default DocumentTitle;
